<!--执行任务 -->
<template>
  <!-- <a-drawer
    title="执行任务"
    :width="1100"
    :visible="drawerVisible"
    :maskClosable="drawMaskClosable==true"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeApplyComplete"
  > -->
<a-drawer
    title="执行任务"
    :width="1100"
    :visible="drawerVisible"
    :maskClosable="drawMaskClosable"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeD"
  >
    <div class="first">{{ taskName }}</div>
    <div class="basicAttr">
      <div class="attr">基本属性</div>
      <div v-if="messageList.length !== 0">
        <div class="messageContent" v-for="(item, index) in messageList" :key="index">
          <div v-for="item1 in item.items" class="message_de" :key="item1.id">
            <detailMessage :attrList="item1"></detailMessage>
          </div>
        </div>
      </div>
      <a-empty v-else description="暂无数据" class="nodata"/>
    </div>
    <div class="deliverable">
      <div class="attr">交付物</div>
      <!-- <div style="margin-bottom: 10px;">
        <a-button type="primary" @click="startSgin">启动签审</a-button>&nbsp;&nbsp;
        <a-button @click="addDeliverRequire">新增交付物要求</a-button>
      </div> -->
      <!-- <taskTable ref="carryTaskDeTable" :table-data="tableData" :load-visible="loadingVisible" :data-row-key="deliverTableKey"
                 :is-rows-select-visible="isRowsSelectVisible" :row-selection="rowSelection"
                 table-name="执行任务" @selectRowsEvent="selectRowsEvent" @routerRequireDel="routerRequireDel"
                 @uploadFile="uploadFile"></taskTable> -->
      
      <a-table :columns="deliverCols" :data-source="tableData" :pagination='{pageSize:5}'>
        <!-- <template slot="deliverableName" slot-scope="text, record, index">
          <a-input v-if="!text" v-model="inputValue" @blur="onBlurChange" />
          <a v-else style="margin-right: 5px;" @click="routerRequireDel(record)">{{ text }}</a>
        </template> -->
        <!-- <template slot="subjectName" slot-scope="text, record, index">
          <span v-if="!text && record['deliverable.name']" class='go-upload' @click='uploadBtn(record)'>上传</span>
          <span v-else>{{ text }}</span>
        </template> -->
      </a-table>
      <upload-delivery v-if="uploadVisible" :upload-modal-visible="uploadVisible" @closeUploadModal='closeUploadModal'
                         @submitDeliver='submitDeliverHandler'></upload-delivery>
    </div>
    <div class="footer">
      <a-button :style="{ marginRight: '8px' }" @click="closeApplyComplete">
        取消
      </a-button>
      <a-button type="primary" @click="commitApplyCompleteTwo">
        确认
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
import detailMessage from "@/components/singlePage/detailMessage";
import taskTable from "./comp/taskTable.vue";
import _ from 'lodash'
import uploadDelivery from '@/components/uploadDelivery/index'
import { createDeliverInfo } from "@api/planComponent";
import {
  getAttributeGroup,
  getDeliverableList,
  getLastResourceHour,
  updateDeliverabeSubject
} from "@api/todoPage";
export default {
  name: "carryTask",
  components: {
    detailMessage, 
    taskTable,
    uploadDelivery
  },
  props: {
    drawerVisible_p: {
      type: Boolean,
      default: false
    },//是否展示抽屉
    oid: {
      type: String,
      default: 'OR:com.pisx.pmgt.project.PIProject:1080235'
    },//任务id
    taskName: {
      type: String,
      default: '产品定义评审'
    },//任务名称
    assignmentOid: {
      type: String,
      default: 'OR:com.pisx.pmgt.assignment.PIResourceAssignment:1684958'
    },
    dataStatus: {
      type: String,
      default: '已完成'
    },
    action: {
      type: String,
      default: '执行任务'
    },//当点击”操作“时显示详情；点击”任务名称“，显示详情+申请完成
    isHaveDelive: {
      type: String,
      default: '否'
    },//是否有交付物
    drawMaskClosable: {
      type: Boolean,
      default: true
    },//点击蒙层是否允许关闭
  },
  data() {
    return {
      textareaValue: "",//情况说明
      drawerVisible: this.drawerVisible_p,
      messageList: [],//基本属性（对象布局与属性）
      /*tableColumns: [
        /!*{
          title: "交付物要求",
          dataIndex: "name",
          scopedSlots: {customRender: "name"}
        },*!/
      ],*/
      tableData: [],
      perc: 10,//完成百分比
      minPerc: 10,//完成百分比最小值
      days: 0,//实际工期
      deliverableStatus: false,//交付物状态全部已完成
      loadingVisible: false,
      isRowsSelectVisible: true,//是否显示复选框
      rowSelection: false,//交付物是否显示多选
      deliverTableKey: 'deliverable.oid',//交付物表格的key
      selectRowsDeliver: [],//选中的数据--交付物
      /**新增交付物要求 */
      deliverCols: [
        {
          title: "交付物要求",
          dataIndex: "deliverable.name",
          width: '22%',
          slotType: 'showspan',
          scopedSlots: {customRender: "deliverableName"}
        },
        {
          title: "交付物",
          dataIndex: "subject.name",
          width: '40%',
          slotType: 'upload',
          scopedSlots: {customRender: "subjectName"}
        },
        {
          title: "是否最新版本",
          dataIndex: "deliverable.lastVersion",
          width: '19%',
        },
        {
          title: "交付物状态",
          dataIndex: "deliverable.targetStatus",
          width: '19%',
        }
      ],
      uploadVisible: false, // 下载弹框显隐
      inputValue: '', // input的值
      upRecord: {}, // 上传那一行的record
      // confirmModel: false, // 确认添加交付物弹框显隐
      // requireStstus: false, // 点击确认的时候，判断失去焦点事件
    }
  },
  computed: {
    slotColumns() {
      return this.deliverCols.filter(item => item.slotType != undefined)
    },
  },
  watch: {
    drawerVisible_p(val) {
      this.drawerVisible = val;
    },
    oid(val) {
      this.oid = val
    },
  },
  mounted() {
    this.getInfo()
    // this.getDeliverableHeader()
    this.getDeliverableData()
    this.getLastResourceHourB()
  },
  methods: {
    closeD(){
        this.$emit('closeDraw')
    },
    closeApplyComplete() {
      this.perc = null
      this.days = null
      this.textareaValue = ''
      this.$emit("closeDraw");
      // this.addDliversTwo()
    },
    commitApplyCompleteTwo() {
      /*新增交付物要求，在输入框获取焦点，但是未输入内容的时候，点击确认，会提示输入*/
      // if (!this.requireStstus) {
      //   return
      // }
        this.$emit("closeDraw");
      // this.addDlivers()
    },
    //获取任务基本信息
    getInfo() {
      let parms = {
        // oid: "OR:com.pisx.pmgt.project.PIProject:1080235"
        oid: this.oid
      }
      getAttributeGroup(parms).then(res => {
        // console.log(res.data[0].rows)
        if (res && res.status === 200) {
          if (res.data && res.data.success) {
            if (res.data.data[0] && res.data.data[0].rows && res.data.data[0].rows.length > 0) {
              this.messageList = res.data.data[0].rows
            } else {
              this.messageList = []
            }
          } else {
            this.messageList = []
            this.$message.error(res.data.message)
          }
        } else {
          this.$message.error('接口失败')
        }
      })
    },
    //获取交付物表格数据
    getDeliverableData() {
      this.loadingVisible = true
      // console.log('获取交付物表格数据--oid:', this.oid)
      let parms = {
        // oid: "OR:com.pisx.pmgt.plan.PIPlanActivity:1364663"
        oid: this.oid
      }
      getDeliverableList(parms).then(res => {
          this.tableData = []
          // console.log(res)
          if (res && res.status === 200) {
            if (res.data && res.data.success) {
              if (res.data.data && res.data.data.length > 0) {
                this.tableData = res.data.data
                // this.deliverTableKey = 'deliverable.oid'
                /*let status = res.data.data.map(rec => {
                  return rec['deliverable.targetStatus']
                })*/
                // 交付物状态：['已发放A','已发放B','已发放C']
                let status = _.filter(res.data.data, (rec) => {
                  return rec['deliverable.targetStatus'].indexOf("已发放") < 0
                })
                // console.log('status-----------------',status)
                if (status.length > 0) {
                  this.deliverableStatus = false
                } else {
                  this.deliverableStatus = true
                }
                this.loadingVisible = false
              } else {
                this.tableData = []
                this.loadingVisible = false
              }
            } else {
              this.loadingVisible = false
              this.$message.error(res.data.message)
            }
          } else {
            this.loadingVisible = false
            this.$message.error('接口失败')
          }
        }
      )
    },
    //获取上一次汇报工时的记录
    getLastResourceHourB() {
      let parm = {
        "resources": [
          {
            "assignmentOid": this.assignmentOid
          }
        ]
      }
      getLastResourceHour(parm).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.success && res.data.data.length > 0) {
            this.perc = res.data.data[0].completePercent
            this.minPerc = res.data.data[0].completePercent
            this.days = res.data.data[0].completeTime
            this.textareaValue = ''
          } else {
            this.perc = null
            this.minPerc = null
            this.days = null
            this.textareaValue = ''
          }
        } else {
          this.$message.error('获取上一次的完成百分比失败')
        }
      })
    },
    //点击交付物--跳转至交付物详情页面
    routerRequireDel(val) {
      //交付物页面（详情界面）
      let fileSingleTableItem_s = {
        oid: val['subject.oid'],//流程oid
        workItemName: '',//流程节点名称
        state: '',//流程状态
        // pboOid: val['deliverable.oid'],//交付物id
        workItemState: val['deliverable.targetStatus']//交付物状况
      }
      sessionStorage.setItem("fileSingleTableItem", JSON.stringify(fileSingleTableItem_s))
      this.$store.commit('SET_PROJECT_FILE_TITLE', '')
      this.$router.push({
        path: '/single/fileSingle/examineProject',
      })
    },
    //获取选中的数据
    selectRowsEvent(val) {
      // console.log('选中的数据', val)
      this.selectRowsDeliver = val
    },
    //启动签审
    startSgin() {
      // console.log('启动签审----------------')
      if (this.selectRowsDeliver.length < 1) {
        this.$message.error('请选择交付物！')
        return
      } else {
        let stateData = _.filter(this.selectRowsDeliver, (o) => {
          return o['deliverable.targetStatus'].indexOf('正在工作') < 0
        })
        let checkOutData = _.filter(this.selectRowsDeliver, (o) => {
          return o['subject.isCheckOut'] == 'true'
        })
        if (stateData.length > 0 || checkOutData.length > 0) {
          this.$message.error('请选择正在工作并且未检出的文档！')
          return;
        }
        console.log('-----------------------------------')
        let newSelectDeliverData = [], newSelectDeliverDataOnce = {}
        this.selectRowsDeliver.map((item) => {
          newSelectDeliverDataOnce.oid = item['subject.oid']
          newSelectDeliverDataOnce.type = item['subject.type']
          newSelectDeliverData.push(newSelectDeliverDataOnce)
        })
        let sessArr = {
          tableArr: newSelectDeliverData
        }
        sessionStorage.setItem('fileSingleDataByStart', JSON.stringify(sessArr))
        this.$router.push('single/fileSingle/fileStart');
      }
    },
    //上传交付物点击“确定”执行的操作
    uploadFile(val, thisRecord) {
      // console.log('选择的交付物-----', val)
      let parm={
        deliverableOid: thisRecord['deliverable.oid'],//当前交付物的deliverable.oid
        subjectOid: val.oid
      }
      updateDeliverabeSubject(parm).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.success) {
            this.$message.success('上传成功！')
            this.getDeliverableData()
            this.$refs.carryTaskDeTable.closeUploadModal()
          } else {
            this.$message.success('上传失败！')
          }
        } else {
          this.$message.error('接口失败')
        }
      })
    },
    /**新增交付物要求 */
    addDeliverRequire() {
      // this.requireStstus = false
      this.tableData.push({
        'deliverable.name': '',
        'subject.name': '',
        'deliverable.lastVersion': '',
        'deliverable.targetStatus': '',
      })
    },
    /*调用接口 */
    addDlivers() {
      let data = {
        oid: this.oid, 
        name: this.inputValue, 
        subjectOid: "", 
      }
      createDeliverInfo(data).then(res => {
        if (res && res.data.success) {
          this.$message.success('添加成功')
          this.getDeliverableData()
          this.$emit("closeDraw");
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    /*调用接口 */
    addDliversTwo() {
      let data = {
        oid: this.oid, 
        name: this.inputValue, 
        subjectOid: "", 
      }
      createDeliverInfo(data).then(res => {
        if (res && res.data.success) {
          this.$message.success('添加成功')
          this.getDeliverableData()
          // this.$emit("closeDraw");
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    /**输入框失去焦点 */
    onBlurChange() {
      let arr = this.tableData.filter(v =>{
        return  v['deliverable.name'] === ''
      })
      if (arr.length > 0 && !this.inputValue) {
        this.$message.error('请输入交付物要求名称')
        return
      }
      // this.confirmModel = true
    },
    // confirm() {
    //   this.addDlivers()
    //   this.confirmModel = false
      // this.requireStstus = false
    // },
    // cancel() {
    //   this.confirmModel = false
    // },
    uploadBtn(record) {
      this.upRecord = record
      this.uploadVisible = true
    },
    //关闭上传交付物弹窗
    closeUploadModal() {
      this.uploadVisible = false
    },
    submitDeliverHandler(val) {
      this.uploadVisible = false
      this.uploadFile(val, this.upRecord)
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ant-drawer-body {
  padding: 10px 20px;
}
.attr {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  margin-bottom: 10px;
}
.first {
  color: rgba(0, 0, 0, 0.85);
  font-size: 20px;
  font-weight: 500;
}
.basicAttr {
  margin-top: 20px;
  .message {
    padding: 5px 20px 5px 0;
  }
}
.deliverable {
  margin-top: 20px;
}
.applyAchieve {
  width: 700px;
  margin-top: 20px;
  /deep/ .ant-row {
    margin-bottom: 10px;
  }
  .label {
    margin-top: 0px;
  }
  .appInput {
    width: 100%;
    margin-top: 10px;
  }
}
.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}
.messageContent {
  margin-bottom: 10px;
  display: flex;
  .message_de {
    width: 25%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .messageList {
      min-width: 25%;
      margin: 5px 0;
      font-size: 14px;
      text-align: right;
      display: flex;
      justify-content: flex-start;
    }
  }
}
.nodata {
  padding: 10px 0 20px 0;
}
.go-upload {
  display: inline-block;
  border: 1px solid #386bd7;
  background: #386bd7;
  color: #fff;
  padding: 0 10px;
  cursor: pointer;
  font-size: 12px;
}
</style>